package com.h3bpm.starcharge.common.uitl.ems;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.h3bpm.starcharge.common.bean.Bestsign_file;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadToServer extends ControllerBase {
     private static final Logger log = LoggerFactory.getLogger(UploadToServer.class);

//    @Value("${documectPort}")
//    private static String documectPort;
//
//    @Value("${documectPost}")
//    private static String documectPost;


    private static String codeEnding = "UTF-8";

    private static String filePath = "D:/";


    public static  String postFileToEMS (Bestsign_file bestsignFile, String postUrl )  {
        Map<String, String> param = new HashMap<>(6);
        String res = "";
        param.put("file_name",bestsignFile.getFileName());
        param.put("proc_no",bestsignFile.getInstanceId());
        try {
            InstanceData instanceData = new InstanceData(getEngine(), bestsignFile.getInstanceId(), User.AdministratorID);
            param.put("creator",instanceData.getInstanceContext().getOriginatorName());
            param.put("approvor","曹晓琭");
        } catch (Exception e) {
            e.printStackTrace();
        }
        param.put("proc_status","已完成");
        param.put("remark",bestsignFile.getContractId());
        File tmpFile = new File(filePath + bestsignFile.getContractId() +"."+ bestsignFile.getFileName().split("\\.")[1]);
        try {
            FileUtils.writeByteArrayToFile(tmpFile,bestsignFile.getContent(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
          res =  postFile(param,tmpFile,postUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("========pushAttachment====="+res);
        tmpFile.delete();
        return res;
    }


    /**
     *
     * @param param
     * file_name 文件名称或附件简称
     * proc_no 流程编号
     * proc_status 流程状态
     * creator 发起人
     * approvor 审批人
     * remark 备注
     * @param file
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
     public static String postFile(Map<String, String> param, File file,String postUrl) throws IllegalArgumentException,IOException {
            String res = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(postUrl);
             MultipartEntityBuilder builder = MultipartEntityBuilder.create();
             builder.addBinaryBody("file", file);
             for (String key : param.keySet()) {

                 builder.addTextBody(key, param.get(key));
             }
            // 生成 HTTP POST 实体
            HttpEntity requestEntity = builder.build();
            //设置请求参数
            httpPost.setEntity(requestEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                res = EntityUtils.toString(responseEntity,codeEnding);
                response.close();
            } else {
                res = EntityUtils.toString(responseEntity,codeEnding);
                response.close();
                throw new IllegalArgumentException(res);
            }
            return res;
        }
     


    @Override
    public String getFunctionCode() {
        return null;
    }
}